<template>
  <div v-if="userInfo" class="user-dropdown" ref="dropdownRef">
    <div 
      class="user-trigger"
      @click="toggleDropdown"
    >
      <div class="user-avatar">{{ userInfo.avatar || '👤' }}</div>
      <div class="user-name">{{ userInfo.name || userInfo.username }}</div>
    </div>

    <div v-if="isOpen" class="dropdown-menu">
      <div class="dropdown-header">
        <div class="user-avatar-large">{{ userInfo.avatar || '👤' }}</div>
        <div class="user-details">
          <div class="user-display-name">{{ userInfo.name || userInfo.username }}</div>
          <div v-if="userInfo.email" class="user-email">{{ userInfo.email }}</div>
          <div v-if="userInfo.role" class="user-role">
            {{ userInfo.role === 'admin' ? '管理员' : '普通用户' }}
          </div>
        </div>
      </div>
      
      <div class="dropdown-divider"></div>
      
      <div class="dropdown-item" @click="handleLogout">
        <span class="item-icon">🚪</span>
        <span class="item-text">退出登录</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { authAPI } from '../services/api'
import { dropdownManager } from '../utils/dropdownManager'
import { getStorageItem, clearAuthStorage } from '../utils'
import { STORAGE_KEYS } from '../constants'
import type { UserInfo } from '../types'

const router = useRouter()
const DROPDOWN_ID = 'user-dropdown'

const isOpen = ref(false)
const userInfo = ref<UserInfo | null>(null)
const dropdownRef = ref<HTMLElement | null>(null)
let autoCloseTimer: number | null = null
let unsubscribe: (() => void) | null = null

const toggleDropdown = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    dropdownManager.notifyOpen(DROPDOWN_ID)
  }
}

const handleLogout = async () => {
  if (window.confirm('确定要退出登录吗？')) {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('Logout failed:', error)
    } finally {
      // 无论登出是否成功，都清除本地存储并跳转到登录页
      clearAuthStorage()
      router.push('/login')
    }
  }
}

const handleMouseEnter = () => {
  if (autoCloseTimer) {
    clearTimeout(autoCloseTimer)
    autoCloseTimer = null
  }
}

const handleMouseLeave = () => {
  autoCloseTimer = window.setTimeout(() => {
    isOpen.value = false
  }, 2000)
}

const handleClickOutside = (event: MouseEvent) => {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target as Node)) {
    isOpen.value = false
  }
}

watch(isOpen, (newValue) => {
  const dropdownElement = dropdownRef.value
  if (dropdownElement && newValue) {
    dropdownElement.addEventListener('mouseenter', handleMouseEnter)
    dropdownElement.addEventListener('mouseleave', handleMouseLeave)
    document.addEventListener('mousedown', handleClickOutside)
    
    autoCloseTimer = window.setTimeout(() => {
      isOpen.value = false
    }, 2000)
  } else if (dropdownElement) {
    dropdownElement.removeEventListener('mouseenter', handleMouseEnter)
    dropdownElement.removeEventListener('mouseleave', handleMouseLeave)
    document.removeEventListener('mousedown', handleClickOutside)
    if (autoCloseTimer) {
      clearTimeout(autoCloseTimer)
    }
  }
})

onMounted(() => {
  // 使用工具函数获取用户信息
  const storedUserInfo = getStorageItem<UserInfo>(STORAGE_KEYS.USER_INFO)
  if (storedUserInfo) {
    userInfo.value = storedUserInfo
  } else {
    const username = getStorageItem<string>(STORAGE_KEYS.USERNAME)
    if (username) {
      userInfo.value = {
        username,
        name: username,
        avatar: '👤'
      }
    }
  }
  
  unsubscribe = dropdownManager.subscribe((openedId) => {
    if (openedId !== DROPDOWN_ID) {
      isOpen.value = false
    }
  })
})

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe()
  }
  if (autoCloseTimer) {
    clearTimeout(autoCloseTimer)
  }
})
</script>

<style scoped>
@import './UserDropdown.css';
</style>